package com.wz.jaav.rtda;

import com.wz.jaav.rtda.heap.Object;
import com.wz.jaav.util.ByteArrayConveter;

import java.util.Arrays;

public class LocalVars {
    private Slot[] slots;

    public LocalVars(int maxLocals){
        if (maxLocals > 0){
            slots = new Slot[maxLocals];
        }
    }

    public void setRef(int index, Object ref){
        this.slots[index] = new Slot();
        this.slots[index].setRef(ref);
    }

    public Object getRef(int index){
        return this.slots[index].getRef();
    }


    public void setFloat(int index, float val){
        this.slots[index] = new Slot();
        this.slots[index].setNum(ByteArrayConveter.getByteArray(val));
    }

    public float getFloat(int index){
        return ByteArrayConveter.getFloat(slots[index].getNum(), 0);
    }

    public void setInt(int index, int val){
        this.slots[index] = new Slot();
        this.slots[index].setNum(ByteArrayConveter.getByteArray(val));
    }

    public int getInt(int index){
        Slot slot = this.slots[index];
        return ByteArrayConveter.getInt(this.slots[index].getNum(), 0);
    }

    public void setLong(int index, long num){
        byte[] numArray = ByteArrayConveter.getByteArray(num);
        push64bitNum(index, numArray);
    }

    public long getLong(int index){
        byte[] higherByte = this.slots[index].getNum();
        byte[] lowerByte = this.slots[index + 1].getNum();
        return ByteArrayConveter.synthesisIntoLong(higherByte, lowerByte);
    }

    public void setDouble(int index, double num){
        byte[] numArray = ByteArrayConveter.getByteArray(num);
        push64bitNum(index, numArray);
    }

    public double getDouble(int index){
        byte[] lowerByte = this.slots[index].getNum();
        byte[] higherByte = this.slots[index + 1].getNum();
        return ByteArrayConveter.synthesisIntoDouble(higherByte, lowerByte);
    }

    private void push64bitNum(int index, byte[] numArray){
        this.slots[index] = new Slot();
        this.slots[index].setNum(ByteArrayConveter.getLowerByte32(numArray));
        this.slots[index + 1] = new Slot();
        this.slots[index + 1].setNum(ByteArrayConveter.getHigherByte32(numArray));
    }

    @Override
    public String toString() {
        return "LocalVars{" +
                "slots=" + Arrays.toString(slots) +
                '}';
    }

    public static void main(String[] args) {
        LocalVars lv = new LocalVars(100);
        lv.setDouble(0, -0.00223D);
        System.out.println(lv.getDouble(0));

        lv.setInt(2, -1000);
        System.out.println(lv.getInt(2));

        lv.setFloat(4, -0.3F);
        System.out.println(lv.getFloat(4));
    }
}